package com.xiaozhen.blog.utils;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * @create 2023-05-13 14:31
 */

/**
 * 自定义 Authority解析器
 */
public class CustomAuthorityDeserializer extends JsonDeserializer { //
    @Override
    public Object deserialize(
            JsonParser jsonParser, //JSON解析
            DeserializationContext deserializationContext) // 上下文
            throws IOException, JsonProcessingException {
        ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec(); //得到Object对象
        JsonNode jsonNode = mapper.readTree(jsonParser); // readTree得到TreeNode对象，JsonNode有实现TreeNode接口

        List<GrantedAuthority> grantedAuthorities = new LinkedList<>(); // 返回
        Iterator<JsonNode> elements = jsonNode.elements(); // 得到迭代器

        while (elements.hasNext()) {
            JsonNode next = elements.next();
            JsonNode authority = next.get("authority"); //需要对这个字段进行解析
            grantedAuthorities.add(new SimpleGrantedAuthority(authority.asText()));
        }
        return grantedAuthorities;
    }
}


